<?php

namespace app\controller\crm;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

/**
 * 客户审核管理控制器
 */
class CustomerReview extends BaseController
{
    /**
     * 获取客户审核列表（包括客户信息审核和联系人审核）
     */
    public function list()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $status = $params['status'] ?? '';
        $reviewType = $params['review_type'] ?? ''; // customer=客户审核, contact=联系人审核
        $keyword = $params['keyword'] ?? '';
        
        $result = [
            'list' => [],
            'total' => 0
        ];
        
        // 客户审核列表
        if (empty($reviewType) || $reviewType === 'customer') {
            $customerReviews = $this->getCustomerReviews($page, $limit, $status, $keyword);
            if ($reviewType === 'customer') {
                return $this->paginate($customerReviews['list'], $customerReviews['total'], (int)$page, (int)$limit);
            }
            $result['list'] = array_merge($result['list'], $customerReviews['list']);
            $result['total'] += $customerReviews['total'];
        }
        
        // 联系人审核列表
        if (empty($reviewType) || $reviewType === 'contact') {
            $contactReviews = $this->getContactReviews($page, $limit, $status, $keyword);
            if ($reviewType === 'contact') {
                return $this->paginate($contactReviews['list'], $contactReviews['total'], (int)$page, (int)$limit);
            }
            $result['list'] = array_merge($result['list'], $contactReviews['list']);
            $result['total'] += $contactReviews['total'];
        }
        
        // 按创建时间倒序排序
        usort($result['list'], function($a, $b) {
            return strtotime($b['create_time']) - strtotime($a['create_time']);
        });
        
        // 分页处理
        $result['list'] = array_slice($result['list'], ($page - 1) * $limit, $limit);
        
        return $this->paginate($result['list'], $result['total'], (int)$page, (int)$limit);
    }
    
    /**
     * 获取客户信息审核列表
     */
    private function getCustomerReviews($page, $limit, $status, $keyword)
    {
        // 检查legal_person字段是否存在
        $hasLegalPersonField = $this->checkFieldExists('crm_customer', 'legal_person');
        
        $fieldStr = $hasLegalPersonField 
            ? 'r.*, u.name as user_name, c.name as customer_name, c.legal_person'
            : 'r.*, u.name as user_name, c.name as customer_name';
        
        $query = Db::name('crm_customer_review')
            ->alias('r')
            ->field($fieldStr)
            ->leftJoin('admin u', 'r.user_id = u.id')
            ->leftJoin('crm_customer c', 'r.customer_id = c.id');
        
        if ($status !== '') {
            $query->where('r.status', $status);
        }
        
        if ($keyword) {
            // 优化关键词搜索逻辑
            $query->where(function($q) use ($keyword, $hasLegalPersonField) {
                $q->where('c.name', 'like', "%{$keyword}%");
                if ($hasLegalPersonField) {
                    $q->whereOr('c.legal_person', 'like', "%{$keyword}%");
                }
                $q->whereOr('r.new_data', 'like', "%{$keyword}%");
            });
        }
        
        $total = $query->count();
        $list = $query->order('r.create_time', 'desc')
            ->page($page, $limit)
            ->select();
        
        // 添加审核类别标识和处理数据
        $list = $list ? $list->toArray() : [];
        foreach ($list as &$item) {
            $item['category'] = 'customer';
            $item['review_type_text'] = $this->getReviewTypeText($item['review_type']);
            
            // 如果customer_name为空，从new_data中解析
            if (empty($item['customer_name']) && !empty($item['new_data'])) {
                $newData = json_decode($item['new_data'], true);
                $item['customer_name'] = $newData['name'] ?? '';
            }
            
            // 如果legal_person为空或字段不存在，从new_data中解析
            if (empty($item['legal_person']) && !empty($item['new_data'])) {
                $newData = json_decode($item['new_data'], true);
                $item['legal_person'] = $newData['legal_person'] ?? '';
            }
            
            // 格式化时间
            $item['create_time'] = $this->formatTime($item['create_time']);
            $item['update_time'] = $this->formatTime($item['update_time']);
        }
        
        return ['list' => $list, 'total' => $total];
    }
    
    /**
     * 获取联系人审核列表
     */
    private function getContactReviews($page, $limit, $status, $keyword)
    {
        $query = Db::name('crm_contact_review')
            ->alias('r')
            ->field('r.*, u.name as user_name, c.name as contact_name, cu.name as customer_name')
            ->leftJoin('admin u', 'r.user_id = u.id')
            ->leftJoin('crm_contact c', 'r.contact_id = c.id')
            ->leftJoin('crm_customer cu', 'r.customer_id = cu.id');
        
        if ($status !== '') {
            $query->where('r.status', $status);
        }
        
        if ($keyword) {
            $query->where(function($q) use ($keyword) {
                $q->where('cu.name', 'like', "%{$keyword}%")
                  ->whereOr('c.name', 'like', "%{$keyword}%")
                  ->whereOr('r.new_data', 'like', "%{$keyword}%");
            });
        }
        
        $total = $query->count();
        $list = $query->order('r.create_time', 'desc')
            ->page($page, $limit)
            ->select();
        
        // 添加审核类别标识和处理数据
        $list = $list ? $list->toArray() : [];
        foreach ($list as &$item) {
            $item['category'] = 'contact';
            $item['review_type_text'] = $this->getReviewTypeText($item['review_type']);
            
            // 如果字段为空，从new_data中解析
            if (!empty($item['new_data'])) {
                $newData = json_decode($item['new_data'], true);
                if (empty($item['contact_name'])) {
                    $item['contact_name'] = $newData['name'] ?? '';
                }
            }
            
            // 格式化时间
            $item['create_time'] = $this->formatTime($item['create_time']);
            $item['update_time'] = $this->formatTime($item['update_time']);
        }
        
        return ['list' => $list, 'total' => $total];
    }
    
    /**
     * 获取审核详情
     */
    public function detail()
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;
        $category = $params['category'] ?? 'customer'; // customer 或 contact
        
        if (!$id) {
            return $this->error('参数错误');
        }
        
        $table = $category === 'contact' ? 'crm_contact_review' : 'crm_customer_review';
        
        $review = Db::name($table)
            ->alias('r')
            ->field('r.*, u.name as user_name, ru.name as reviewer_name')
            ->leftJoin('admin u', 'r.user_id = u.id')
            ->leftJoin('admin ru', 'r.review_user_id = ru.id')
            ->where('r.id', $id)
            ->find();
        
        if (!$review) {
            return $this->error('审核记录不存在');
        }
        
        // 解析JSON数据
        $review['original_data'] = $review['original_data'] ? json_decode($review['original_data'], true) : null;
        $review['new_data'] = $review['new_data'] ? json_decode($review['new_data'], true) : null;
        $review['category'] = $category;
        $review['review_type_text'] = $this->getReviewTypeText($review['review_type']);
        $review['status_text'] = $this->getStatusText($review['status']);
        
        // 获取客户名称、法人和联系人名称
        if ($category === 'customer') {
            if ($review['customer_id']) {
                $customer = Db::name('crm_customer')->where('id', $review['customer_id'])->find();
                $review['customer_name'] = $customer['name'] ?? '';
                $review['legal_person'] = $customer['legal_person'] ?? '';
            } elseif (!empty($review['new_data'])) {
                $review['customer_name'] = $review['new_data']['name'] ?? '';
                $review['legal_person'] = $review['new_data']['legal_person'] ?? '';
            }
        } else {
            // 联系人审核
            if ($review['customer_id']) {
                $customer = Db::name('crm_customer')->where('id', $review['customer_id'])->find();
                $review['customer_name'] = $customer['name'] ?? '';
            }
            if ($review['contact_id']) {
                $contact = Db::name('crm_contact')->where('id', $review['contact_id'])->find();
                $review['contact_name'] = $contact['name'] ?? '';
            } elseif (!empty($review['new_data'])) {
                $review['contact_name'] = $review['new_data']['name'] ?? '';
            }
        }
        
        // 格式化时间
        $review['create_time'] = $this->formatTime($review['create_time']);
        $review['update_time'] = $this->formatTime($review['update_time']);
        $review['review_time'] = $this->formatTime($review['review_time']);
        
        return $this->success($review, '获取成功');
    }
    
    /**
     * 审核处理（通过/驳回）
     */
    public function approve()
    {
        $params = Request::param();
        $id = $params['id'] ?? 0;
        $category = $params['category'] ?? 'customer'; // customer 或 contact
        $status = $params['status'] ?? 2; // 2-通过 3-驳回
        $remark = $params['remark'] ?? '';
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        if (!in_array($status, [2, 3])) {
            return $this->error('审核状态参数错误');
        }
        
        // 检查权限（只有超级管理员和部门经理可以审核）
        $userInfo = Db::name('admin')
            ->field('id, group_id')
            ->where('id', $userId)
            ->find();
        
        if (!$userInfo || $userInfo['group_id'] > 2) {
            return $this->error('无审核权限');
        }
        
        Db::startTrans();
        try {
            if ($category === 'contact') {
                $result = $this->approveContactReview($id, $status, $remark, $userId);
            } else {
                $result = $this->approveCustomerReview($id, $status, $remark, $userId);
            }
            
            if ($result['code'] === 0) {
                Db::commit();
                return $this->success($result['msg']);
            } else {
                Db::rollback();
                return $this->error($result['msg']);
            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('审核失败：' . $e->getMessage());
        }
    }
    
    /**
     * 审核客户信息
     */
    private function approveCustomerReview($id, $status, $remark, $userId)
    {
        $review = Db::name('crm_customer_review')->where('id', $id)->find();
        
        if (!$review) {
            return ['code' => 1, 'msg' => '审核记录不存在'];
        }
        
        if ($review['status'] != 1) {
            return ['code' => 1, 'msg' => '该审核已处理'];
        }
        
        // 更新审核状态
        Db::name('crm_customer_review')->where('id', $id)->update([
            'status' => $status,
            'review_user_id' => $userId,
            'review_time' => time(),
            'review_remark' => $remark,
            'update_time' => time()
        ]);
        
        // 如果审核通过，执行相应操作
        if ($status == 2) {
            $newData = json_decode($review['new_data'], true);
            
            if ($review['review_type'] == 1) {
                // 新增客户
                // 移除可能存在的时间字段，避免格式错误
                unset($newData['create_time']);
                unset($newData['update_time']);
                unset($newData['delete_time']);
                
                $newData['create_time'] = time();
                $newData['update_time'] = time();
                $customerId = Db::name('crm_customer')->insertGetId($newData);
                
                // 更新审核记录的customer_id
                Db::name('crm_customer_review')->where('id', $id)->update(['customer_id' => $customerId]);
            } else {
                // 编辑客户
                // 移除可能存在的时间字段，避免格式错误
                unset($newData['create_time']);
                unset($newData['update_time']);
                unset($newData['delete_time']);
                
                $newData['update_time'] = time();
                Db::name('crm_customer')->where('id', $review['customer_id'])->update($newData);
            }
        }
        
        return ['code' => 0, 'msg' => $status == 2 ? '审核通过' : '审核已驳回'];
    }
    
    /**
     * 审核联系人信息
     */
    private function approveContactReview($id, $status, $remark, $userId)
    {
        $review = Db::name('crm_contact_review')->where('id', $id)->find();
        
        if (!$review) {
            return ['code' => 1, 'msg' => '审核记录不存在'];
        }
        
        if ($review['status'] != 1) {
            return ['code' => 1, 'msg' => '该审核已处理'];
        }
        
        // 更新审核状态
        Db::name('crm_contact_review')->where('id', $id)->update([
            'status' => $status,
            'review_user_id' => $userId,
            'review_time' => time(),
            'review_remark' => $remark,
            'update_time' => time()
        ]);
        
        // 如果审核通过，执行相应操作
        if ($status == 2) {
            $newData = json_decode($review['new_data'], true);
            
            if ($review['review_type'] == 1) {
                // 新增联系人
                // 移除可能存在的时间字段，避免格式错误
                unset($newData['create_time']);
                unset($newData['update_time']);
                unset($newData['delete_time']);
                
                $newData['create_time'] = time();
                $newData['update_time'] = time();
                $contactId = Db::name('crm_contact')->insertGetId($newData);
                
                // 更新审核记录的contact_id
                Db::name('crm_contact_review')->where('id', $id)->update(['contact_id' => $contactId]);
            } elseif ($review['review_type'] == 2) {
                // 编辑联系人
                // 移除可能存在的时间字段，避免格式错误
                unset($newData['create_time']);
                unset($newData['update_time']);
                unset($newData['delete_time']);
                
                $newData['update_time'] = time();
                Db::name('crm_contact')->where('id', $review['contact_id'])->update($newData);
            } elseif ($review['review_type'] == 3) {
                // 删除联系人
                Db::name('crm_contact')->where('id', $review['contact_id'])->update([
                    'delete_time' => time()
                ]);
            }
        }
        
        return ['code' => 0, 'msg' => $status == 2 ? '审核通过' : '审核已驳回'];
    }
    
    /**
     * 获取审核类型文本
     */
    private function getReviewTypeText($type)
    {
        $texts = [
            1 => '新增',
            2 => '编辑',
            3 => '删除'
        ];
        return $texts[$type] ?? '未知';
    }
    
    /**
     * 获取审核状态文本
     */
    private function getStatusText($status)
    {
        $texts = [
            1 => '待审核',
            2 => '审核通过',
            3 => '审核驳回'
        ];
        return $texts[$status] ?? '未知';
    }
    
    /**
     * 格式化时间
     */
    private function formatTime($time)
    {
        if (empty($time)) {
            return '';
        }
        
        // 如果是时间戳
        if (is_numeric($time)) {
            return date('Y-m-d H:i:s', $time);
        }
        
        // 如果是日期时间字符串
        if (is_string($time)) {
            $timestamp = strtotime($time);
            if ($timestamp !== false) {
                return date('Y-m-d H:i:s', $timestamp);
            }
        }
        
        return $time;
    }
    
    /**
     * 检查表字段是否存在
     */
    private function checkFieldExists($tableName, $fieldName)
    {
        try {
            $prefix = config('database.connections.mysql.prefix');
            $fullTableName = $prefix . $tableName;
            $dbName = config('database.connections.mysql.database');
            
            $result = Db::query(
                "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?",
                [$dbName, $fullTableName, $fieldName]
            );
            
            return !empty($result);
        } catch (\Exception $e) {
            // 如果查询失败，返回false
            return false;
        }
    }
    
    /**
     * 获取审核统计信息
     */
    public function statistics()
    {
        $userId = $this->getUserId();
        
        // 客户审核统计
        $customerStats = Db::name('crm_customer_review')
            ->field('status, COUNT(*) as count')
            ->group('status')
            ->select()
            ->toArray();
        
        // 联系人审核统计
        $contactStats = Db::name('crm_contact_review')
            ->field('status, COUNT(*) as count')
            ->group('status')
            ->select()
            ->toArray();
        
        $stats = [
            'customer' => [
                'pending' => 0,
                'approved' => 0,
                'rejected' => 0,
                'total' => 0
            ],
            'contact' => [
                'pending' => 0,
                'approved' => 0,
                'rejected' => 0,
                'total' => 0
            ]
        ];
        
        foreach ($customerStats as $item) {
            if ($item['status'] == 1) $stats['customer']['pending'] = $item['count'];
            if ($item['status'] == 2) $stats['customer']['approved'] = $item['count'];
            if ($item['status'] == 3) $stats['customer']['rejected'] = $item['count'];
            $stats['customer']['total'] += $item['count'];
        }
        
        foreach ($contactStats as $item) {
            if ($item['status'] == 1) $stats['contact']['pending'] = $item['count'];
            if ($item['status'] == 2) $stats['contact']['approved'] = $item['count'];
            if ($item['status'] == 3) $stats['contact']['rejected'] = $item['count'];
            $stats['contact']['total'] += $item['count'];
        }
        
        return $this->success($stats, '获取成功');
    }
}
